package cn.maihe.elg.operation.centers.epoint.sanming.auth;

import cn.maihe.elg.operation.centers.epoint.sanming.config.EpointAuthConfig;
import cn.maihe.elg.operation.common.auth.Encryption;
import cn.maihe.elg.operation.config.ElgAuthConfig;
import cn.maihe.elg.operation.exception.CenterException;
import cn.maihe.elg.operation.utils.SM4Util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;

/**
 * @Description SM4
 * @Author WJH
 * @Date 2021/07/12
 */
@Component
public class EpointEncryption implements Encryption {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ElgAuthConfig elgAuthInfo;
    private final EpointAuthConfig epointAuthConfig;
    private final byte[] secretKeyAy;

    public EpointEncryption(ElgAuthConfig elgAuthConfig, EpointAuthConfig epointAuthConfig) {
        this.elgAuthInfo = elgAuthConfig;
        this.epointAuthConfig = epointAuthConfig;
        this.secretKeyAy = Base64.decodeBase64(epointAuthConfig.getSecretKey());
    }


    /**
     * 漳州新点字段加密方式 先sm4 ECB加密后base64编码
     *
     * @param unEncryptedData
     * @return
     */
    @Override
    public byte[] encrypt(byte[] unEncryptedData) {
        try {
            return SM4Util.encrypt_ECB_Padding(secretKeyAy, unEncryptedData);
        } catch (Exception e) {
            throw CenterException.exception("加密失败",e);
        }
    }

    /**
     *  先sm4加密后再base64编码
     * @param unEncryptedData 明文
     * @return
     */
    public String encrypt(String unEncryptedData) {
        Assert.hasText(unEncryptedData, () -> "待加密数据不能为空");
        byte[] enByte = this.encrypt(unEncryptedData.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(enByte);
    }


    /**
     * 平台的私钥解密
     *
     * @param encryptedData
     * @return
     */
    @Override
    public byte[] decrypt(byte[] encryptedData) {
        try {
            return SM4Util.decrypt_ECB_Padding(secretKeyAy, encryptedData);
        } catch (Exception e) {
            throw CenterException.exception("解密失败",e);
        }
    }

    /**
     *  先base64解码后再sm4解密
     * @param encryptedData sm4加密后base64编码字符串
     * @return
     */
    public String decrypt(String encryptedData) {
        Assert.hasText(encryptedData, () -> "待解密数据不能为空");
        byte[] enByte = Base64.decodeBase64(encryptedData);
        byte[] deByte = this.decrypt(enByte);
        return new String(deByte,StandardCharsets.UTF_8);
    }

}
